package com.finace.money;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.StrictMode;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;

import com.finace.money.common.Constant;
import com.finace.money.common.util.ACache;
import com.finace.money.common.util.ACacheClearUtil;
import com.finace.money.common.util.LocaleUtils;
import com.finace.money.common.util.LogUtil;
import com.finace.money.common.util.MessageSendUtil;
import com.finace.money.common.util.StringUtil;
import com.finace.money.common.util.UIUtil;
import com.finace.money.di.component.AppComponent;
import com.finace.money.di.component.DaggerAppComponent;
import com.finace.money.di.module.AppModule;
import com.finace.money.di.module.HttpModule;
import com.finace.money.net.socket.ConnService;
import com.finace.money.ui.activity.LoginActivity;
import com.finace.money.ui.activity.SplashActivity;

import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by zhangpeng on 2017/11/20.
 */

public class App extends MultiDexApplication {
    //环境 1:线下环境 2:线上测试 3:正式环境
    public static final int FORMAL_ENVIRONMENT = 1;
    public static boolean LogFlag;

    private static App mContext;

    public static Activity mForegroundActivity;

    private static Handler mMainHandler;

    private static Thread mMainThread;

    private static int mMainThreadId;

    private static Looper mMainThreadLooper;

    private AppComponent mAppComponent;

    private int mFinalCount = 0;

    @Override
    public void onCreate() {
        super.onCreate();

        Locale _UserLocale= LocaleUtils.getUserLocale(this);
        LocaleUtils.updateLocale(this, _UserLocale);

        Intent intent = new Intent(this, ConnService.class);
        startService(intent);
        mAppComponent = DaggerAppComponent.builder().appModule(new AppModule(this))
                .httpModule(new HttpModule()).build();
        switch (FORMAL_ENVIRONMENT) {
            case 1:
                //线下
                LogFlag = true;
                break;
            case 2:
                //线上测试
                LogFlag = true;
                break;
            case 3:
                //正式
                LogFlag = false;
                break;
        }

        mContext = (App) getApplicationContext();
        mMainHandler = new Handler();
        mMainThread = Thread.currentThread();
        mMainThreadId = android.os.Process.myTid();
        mMainThreadLooper = getMainLooper();


        //7.0系统通过uri访问时设置，防止文件不能访问
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {

            @Override
            public void onActivityCreated(Activity activity, Bundle bundle) {
            }

            @Override
            public void onActivityStarted(final Activity activity) {
                    mFinalCount++;
                    //如果mFinalCount ==1，说明是从后台到前台
                    if (mFinalCount == 1){
                        String login = ACache.get(UIUtil.getContext()).getAsString(Constant.login);
                        if(StringUtil.isNotNullString(login)){
                            MessageSendUtil.HeartBeatRequest();
                            new Timer().schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    String loginHeart = ACache.get(UIUtil.getContext()).getAsString(Constant.LOGIN_HEART);
                                    if(StringUtil.isNullString(loginHeart)){
                                        ACacheClearUtil.loginOut();
                                        if(!(activity instanceof SplashActivity)){
                                            Intent intent = new Intent(UIUtil.getContext(), LoginActivity.class);
                                            startActivity(intent);
                                        }
                                    }else {
                                        loginHeart = null;
                                        ACache.get(UIUtil.getContext()).put(Constant.LOGIN_HEART, loginHeart);
                                    }
                                }
                            }, 2000);
                        }
                    }

            }

            @Override
            public void onActivityResumed(final Activity activity) {

            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {
                    mFinalCount--;
                    //如果mFinalCount ==0，说明是前台到后台
                    if (mFinalCount == 0){

                    }
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                LogUtil.d("APP",activity.getLocalClassName()+"被杀死了");
                /*if(activity instanceof MainActivity){
                    ACacheClearUtil.loginOut();
                }*/
            }
        });


    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Locale _UserLocale=LocaleUtils.getUserLocale(this);
        //系统语言改变了应用保持之前设置的语言
        if (_UserLocale != null) {
            Locale.setDefault(_UserLocale);
            Configuration _Configuration = new Configuration(newConfig);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                _Configuration.setLocale(_UserLocale);
            } else {
                _Configuration.locale =_UserLocale;
            }
            getResources().updateConfiguration(_Configuration, getResources().getDisplayMetrics());
        }
    }

    /**
     * 获取全局上下文
     *
     * @return
     */
    public static App getApplication() {
        return mContext;
    }

    /**
     * 获取主线程handler
     *
     * @return
     */
    public static Handler getMainThreadHandler() {
        return mMainHandler;
    }

    /**
     * 获取主线程
     *
     * @return
     */
    public static Thread getMainThread() {
        return mMainThread;
    }

    /**
     * 获取主线程id
     *
     * @return
     */
    public static int getMainThreadId() {
        return mMainThreadId;
    }

    /**
     * 获取主线程轮询器
     *
     * @return
     */
    public static Looper getMainThreadLooper() {
        return mMainThreadLooper;
    }


    public static Activity getmForegroundActivity() {
        return mForegroundActivity;
    }

    public static void setmForegroundActivity(Activity mForegroundActivity) {
        App.mForegroundActivity = mForegroundActivity;
    }

    // 获取清单文件的metaData
    private String getMetaDataValue(String key) {
        try {
            ApplicationInfo info = getPackageManager().getApplicationInfo(
                    getPackageName(), PackageManager.GET_META_DATA);
            return info.metaData.getString(key);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 程序是否在前台运行
     *
     * @return
     */
    public static boolean isAppOnForeground(Context context) {
        ActivityManager activityManager = (ActivityManager) context
                .getApplicationContext().getSystemService(
                        Context.ACTIVITY_SERVICE);
        String packageName = context.getApplicationContext().getPackageName();

        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public AppComponent getAppComponent() {

        return mAppComponent;
    }

    /*@Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        switch (level){
            case TRIM_MEMORY_COMPLETE:
                ACache.get(UIUtil.getContext()).clear();
                break;
        }
    }*/
}
